package top.huntwolf.admin.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.huntwolf.admin.common.enums.CodeMsg;
import top.huntwolf.admin.exception.ServiceException;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class TokenUtil {

    private static final String SECRET = "JWT_TOKEN";
    private static final long EXPIRE_TIME = 7 * 24 * 60 * 60 * 1000;
//    private static final long EXPIRE_TIME = 1 * 1000;

    public static String getTokenOpenId(){
        String token = getRequest().getHeader("token");
        return JWT.decode(token).getAudience().get(0);
    }

    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        return requestAttributes == null ? null : requestAttributes.getRequest();
    }

    public static String getUserName(){
        String token = getRequest().getHeader("token");
        return JWT.decode(token).getClaim("userName").asString();
    }



    //CMS端登录使用
    public static String getCMSToken(String userName){
        Date start = new Date();
        //7天有效时间
        Date end = new Date(start.getTime() + EXPIRE_TIME);
        String token = "";
        token = JWT.create().withClaim("userName",userName).withIssuedAt(start).withExpiresAt(end)
                .sign(Algorithm.HMAC256(SECRET));
        return token;
    }

    public static String getCMSUserName(String CMSToken){
//        String CMSToken = getRequest().getHeader("token");
        return JWT.decode(CMSToken).getClaim("userName").asString();
    }

    public static boolean verify(String token,String userName){
        try {
            DecodedJWT jwt = JWT.require(Algorithm.HMAC256(SECRET))
                    .withClaim("userName", userName)
                    .build().verify(token);
            return true;

        }catch (Exception e){
            return false;
        }
    }

}
